package com.biShe.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

//在上述代码中，我们使用`AlipayTradePagePayRequest`创建支付请求，并设置订单信息、同步返回URL和异步通知URL。最后，通过调用`alipayClient.pageExecute(request)`方法，生成支付页面并将页面内容返回。
@Service
public class PayService {
    @Value("${alipay.appId}")
    private String appId;

    @Value("${alipay.gatewayUrl}")
    private String gatewayUrl;

    @Value("${alipay.signType}")
    private String signType;

    @Value("${alipay.charset}")
    private String charset;

    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;

    @Value("${alipay.merchantPrivateKey}")
    private String merchantPrivateKey;

    public String createPayment(String orderId, String totalAmount, String subject, String body, String returnUrl) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, merchantPrivateKey, "json", charset, alipayPublicKey, signType);

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(returnUrl);
        request.setNotifyUrl("http://your-notify-url.com/notify"); // 设置异步通知URL，用于接收支付结果通知
        // 设置订单信息
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderId + "\"," +
                "\"total_amount\":\"" + totalAmount + "\"," +
                "\"subject\":\"" + subject + "\"," +
                "\"body\":\"" + body + "\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"" +
                "}");

        String form = alipayClient.pageExecute(request).getBody(); // 调用接口生成支付页面
//        String regex =  "(?<=action=)[\\s\\S]*(?=>\n" +
//                "<input type=\"hidden\")";//字符串的开头是？ut=，中间的内容是任意字符，结尾是&
//        Pattern pattern = Pattern.compile(regex);
//        Matcher matcher = pattern.matcher(form);
//
//        String group = "";
//        if(matcher.find()){
//            group = matcher.group();
//            System.out.println("截取到内容是：" + group);
//        }

        System.out.println("响应内容是：" + form);
        return form;
    }
}
